global.Request = require('../class/Request.js');
global.Response = require('../class/Response.js');

// 实现路由
WSC.router = {};
WSC.router.messagePurpose = new Map();
WSC.router.event = new Map();
WSC.router.requestId = new Map();
WSC.router.url = new Map();

WSC.onRequestId = (url, callback)=>{
    if (!WSC.router.requestId.has(url)){
        WSC.router.requestId.set(url, [callback]);
    }else{
        WSC.router.requestId.get(url).push(callback);
    }
};

WSC.onMessagePurpose = (url, callback)=>{
    if (!WSC.router.messagePurpose.has(url)){
        WSC.router.messagePurpose.set(url, [callback]);
    }else{
        WSC.router.messagePurpose.get(url).push(callback);
    }
};


WSC.onEvent = (eventName, callback)=>{
    if (!WSC.router.event.has(eventName)){
        WSC.router.event.set(eventName, [callback]);
    }else{
        WSC.router.event.get(eventName).push(callback);
    }
};

WSC.get = (url, callback)=>{
    if (!WSC.router.url.has(url)){
        WSC.router.url.set(url, [callback]);
    }else{
        WSC.router.url.get(url).push(callback);
    }
};

// 实现发送-响应
WSC.pendingRequests = new Map();

// 导出jsonMessage Api接口
WSC.addApiEventName('jsonMessage'); 

WSC.on('message', (client, message_raw)=>{
    let message_json;
    try {
        message_json = JSON.parse(message_raw);
    }catch{
        WSC.logger.error(`JSON解析错误 | 长度: ${message_raw.length}`);
        return false;
    }

    if (CONF.CONFIG.get('Websocket')['Debug'] == true){
        console.log('客户端收到: ', JSON.parse(message_raw), '\n-----------------------\n ');
    }

    // 路由解析
    routerParseAndRun(message_json).catch((err)=>{
        WSC.logger.error(err);
    });
    
    // 发送到llapi接口
    WSC.api.listener.emit('jsonMessage', message_json);
});


async function routerParseAndRun(message_json){
    const request = new Request(message_json); // 请求对象
    const response = Response.fromRequest(request);
   
    // 路由解析requestId
    const requestId = request.header?.requestId;
    if (requestId != undefined){
        // 检查是否为响应消息
        if (requestId && WSC.pendingRequests.has(requestId)) {
            const { successCallback, errorCallback, timeout } = WSC.pendingRequests.get(requestId);
            clearTimeout(timeout); // 清除超时计时器
            WSC.pendingRequests.delete(requestId); // 清理
            if (await successCallback(request, response) === false){ // 执行回调
                return;
            }
        }
        for (const rounter_requestId of WSC.router.requestId.keys()){
            if (typeof(rounter_requestId) === 'string' ? requestId === rounter_requestId : rounter_requestId.test(requestId)){
                let callbackList = WSC.router.requestId.get(rounter_requestId);
                if (Array.isArray(callbackList)){
                    for (let callback of callbackList){
                        if (typeof(callback) != 'function'){continue;}
                        if (await callback(WSC.client, request, response) === false){ // callback返回false则终止之后的路由
                            return;
                        }
                    }
                }
            }
        }
    }

    // 路由解析messagePurpose
    const messagePurpose = request.header?.messagePurpose;
    if (messagePurpose != undefined){
        for (const rounter_messagePurpose of WSC.router.messagePurpose.keys()){
            if (typeof(rounter_messagePurpose) === 'string' ? messagePurpose === rounter_messagePurpose : rounter_messagePurpose.test(messagePurpose)){
                let callbackList = WSC.router.messagePurpose.get(rounter_messagePurpose);
                if (Array.isArray(callbackList)){
                    for (let callback of callbackList){
                        if (typeof(callback) != 'function'){continue;}
                        if (await callback(WSC.client, request, response) === false){ // callback返回false则终止之后的路由
                            return;
                        }
                    }
                }
            }
        }
    }
    
    // 路由解析event（CONSTANTS.MESSAGE_PURPOSE.EVENT类型的 messagePurpose）
    const eventName = request.header?.eventName;
    if (eventName != undefined){
        for (const rounter_eventName of WSC.router.eventName.keys()){
            if (typeof(rounter_eventName) === 'string' ? eventName === rounter_eventName : rounter_eventName.test(eventName)){
                let callbackList = WSC.router.eventName.get(rounter_eventName);
                if (Array.isArray(callbackList)){
                    for (let callback of callbackList){
                        if (typeof(callback) != 'function'){continue;}
                        if (await callback(WSC.client, request, response) === false){ // callback返回false则终止之后的路由
                            return;
                        }
                    }
                }
            }
        }
    }
        
    

    // 路由解析url(CONSTANTS.MESSAGE_PURPOSE.BDS_REQUEST类型的 messagePurpose)
    const url = request.header?.url;
    if (url != undefined){
        for (const rounter_url of WSC.router.url.keys()){
            if (typeof(rounter_url) === 'string' ? url === rounter_url : rounter_url.test(url)){
                let callbackList = WSC.router.url.get(rounter_url);
                if (Array.isArray(callbackList)){
                    for (let callback of callbackList){
                        if (typeof(callback) != 'function'){continue;}
                        if (await callback(WSC.client, request, response) === false){ // callback返回false则终止之后的路由
                            return;
                        }
                    }
                }
            }
        }
    }
}

require('./index.js');

